<template>


  <!-- 表单部分 -->
  <el-card style="height: 600px;">
    <h4>基础数据</h4>
    <el-divider />
    <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="auto">
      <div class="common-layout">
        <el-container>
          <el-header>
            <el-form-item label="货品名称" prop="productName">
              <el-input v-model="ruleForm.productName" style="width: 1180px;" clearable />
            </el-form-item>
          </el-header>
          <el-main>
            <div class="common-layout" style="margin-top: -20px;">
              <el-container>
                <el-aside width="600px">
                  <el-form-item label="货品编号" prop="productCode">
                    <el-input v-model="ruleForm.productCode" style="width: 450px;" placeholder="自动获取系统编号"
                      class="readonly-input" readonly>
                      <template #append>
                        <el-button @click="generateProductCode" :loading="generatingProductCode">
                          自动生成
                        </el-button>
                      </template>
                    </el-input>
                  </el-form-item>
                  <el-form-item label="规格型号" prop="productspecification">
                    <el-input v-model="ruleForm.productspecification" style="width: 450px;" clearable />
                  </el-form-item>
                  <el-form-item label="客户名称" prop="customerId">
                    <el-select v-model="ruleForm.customerId" placeholder="请选择" style="width: 450px;" clearable>
                      <el-option :label="i.customerName" :value="i.customerId" v-for="i in CustomertableData" />
                    </el-select>
                    <span style="margin-left: 5px;color:darkcyan;" @click="router.push({ path: '/CreateCustomer' })">设置</span>
                  </el-form-item>
                  <el-form-item label="出库参考价/元" prop="productOutmoney">
                    <el-input v-model="ruleForm.productOutmoney" style="width: 450px;" clearable />
                  </el-form-item>
                  <el-form-item label="状态" prop="productState">
                    <el-radio-group v-model="ruleForm.productState" style="width: 450px;">
                      <el-radio value="1">启用</el-radio>
                      <el-radio value="2">停用</el-radio>
                    </el-radio-group>
                  </el-form-item>
                  <el-form-item label="保质期" v-if="productShelfdayinfo.check">
                    <el-input v-model="productShelfdayinfo.number" style="width: 340px;margin-right: 10px;" clearable />
                    <el-select v-model="productShelfdayinfo.unit" placeholder="请选择" style="width: 100px;" clearable>
                      <el-option label="天" value="天" />
                      <el-option label="月" value="月" />
                      <el-option label="年" value="年" />
                    </el-select>
                  </el-form-item>

                </el-aside>
                <el-aside width="600px" style="margin-left: 130px;">
                  <el-form-item label="货品类型" prop="producttypeId">
                    <el-tree-select v-model="ruleForm.producttypeId" :data="ProductTypeTreeData"
                      :props="{ value: 'id', label: 'label', children: 'children' }" check-strictly clearable filterable
                      placeholder="请选择" style="width: 450px;" />
                    
                  </el-form-item>
                  <el-form-item label="供应商" prop="supplierId">
                    <el-select v-model="ruleForm.supplierId" placeholder="请选择" style="width: 450px;" clearable>
                      <el-option :label="i.supplierName" :key="i.supplierId" :value="i.supplierId"
                        v-for="i in SupplietableData" />
                    </el-select>
                    <span style="margin-left: 5px;color: darkcyan;" @click="router.push({ path: '/CreateSupplier' })">设置</span>
                  </el-form-item>
                  <el-form-item label="入库参考价/元" prop="productInmoney">
                    <el-input v-model="ruleForm.productInmoney" style="width: 450px;" clearable />
                  </el-form-item>
                  <el-form-item label="显示顺序" prop="productOrderby">
                    <el-input v-model="ruleForm.productOrderby" style="width: 450px;" clearable />
                  </el-form-item>
                  <el-form-item label="保质期管理" prop="productShelf">
                    <el-checkbox v-model="productShelfdayinfo.check" @change="setShelfFields">
                      开启
                    </el-checkbox>
                  </el-form-item>
                  <el-form-item label="预警天数(天)" prop="productWarningDay" v-if="productShelfdayinfo.check">
                    <el-input v-model="ruleForm.productWarningDay" style="width: 450px;" clearable />
                  </el-form-item>
                </el-aside>
              </el-container>
            </div>
          </el-main>
          <el-footer>
            <el-form-item label="备注" prop="productNote">
              <el-input v-model="ruleForm.productNote" style="width: 1180px;" type="textarea" :rows="4" />
            </el-form-item>
          </el-footer>
        </el-container>
      </div>
    </el-form>
  </el-card>


  <!-- 规格表单 -->
  <el-card style="margin-top: 20px;">
    <h4>单位管理</h4>
    <el-divider />
    <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="auto">
      <el-form-item label="主单位" prop="productUnit">
        <el-select v-model="ruleForm.productUnit" placeholder="请选择" style="width: 350px;margin-right: 10px;"
          clearable filterable>
          <el-option v-for="unit in unitOptions" :key="unit.unitId" :label="unit.unitName" :value="unit.unitId" />
        </el-select>
        <el-input v-model="ruleForm.productBarcode" style="width: 300px;" clearable>
          <template #append>
            <span style="color: darkcyan;" @click="GetproductBarcode">生成条形码</span>
          </template>

        </el-input>
      </el-form-item>
    </el-form>
  </el-card>

  <!-- 库存信息 -->
  <el-card class="inventory-card" style="margin-top: 20px; height: 400px;">
    <div class="inventory-header">
      <h4>库存信息</h4>
      <div class="inventory-actions">
        <el-button type="primary" size="small" @click="openDialog">添加</el-button>
        <el-button size="small" @click="removeLast" :disabled="!rows.length">移除</el-button>
        <el-checkbox v-model="showInitial">初始库存</el-checkbox>
      </div>
    </div>

    <el-alert v-if="limitError" type="error" title="库存上限应大于库存下限！" class="inventory-alert" closable
      @close="limitError = false" />

    <el-table :data="rows" border style="width: 100%;height: 300px;" header-cell-class-name="inventory-header-cell">
      <el-table-column type="index" label="序号" width="70" align="center" />

      <el-table-column :label="showInitial ? '期初仓库' : '仓库名称'" min-width="150">
        <template #default="{ row }">
          {{ row.warehouseName }}
        </template>
      </el-table-column>

      <el-table-column v-if="showInitial" label="期初库存" min-width="200">
        <template #default="{ row }">
          <div class="cell-with-action">
            <el-input v-model="row.initialStock" placeholder="请输入" />
            <el-link type="primary" @click="handleBatch('initialStock', row.initialStock)">批量</el-link>
          </div>
        </template>
      </el-table-column>

      <el-table-column v-if="showInitial" label="期初库存金额" min-width="200">
        <template #default="{ row }">
          <el-input v-model="row.initialAmount" placeholder="请输入">
            <template #append>元</template>
          </el-input>
        </template>
      </el-table-column>

      <el-table-column label="库存上限" min-width="200">
        <template #default="{ row }">
          <div class="cell-with-action">
            <el-input v-model="row.upperLimit" placeholder="请输入" />
            <el-link type="primary" @click="handleBatch('upperLimit', row.upperLimit)">批量</el-link>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="库存下限" min-width="200">
        <template #default="{ row }">
          <div class="cell-with-action">
            <el-input v-model="row.lowerLimit" placeholder="请输入" />
            <el-link type="primary" @click="handleBatch('lowerLimit', row.lowerLimit)">批量</el-link>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="备注" min-width="200">
        <template #default="{ row }">
          <el-input v-model="row.remark" placeholder="请输入" />
        </template>
      </el-table-column>

      <el-table-column label="操作" width="100" align="center">
        <template #default="{ $index }">
          <el-button link type="danger" size="small" @click="removeRow($index)">移除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-card>
  <!-- 仓库列表弹框 -->
  <el-dialog v-model="dialogVisible" title="添加仓库" width="80%" top="5vh">
    <div class="dialog-filter">
      <el-input placeholder="请输入仓库编号/名称" class="filter-item" clearable />
      <el-select placeholder="请选择状态" class="filter-item" clearable>
        <el-option label="启用" value="启用" />
        <el-option label="停用" value="停用" />
        <el-option label="已锁定" value="已锁定" />
      </el-select>
      <el-select placeholder="请选择库管部门" class="filter-item" clearable />
      <el-select placeholder="请选择仓库主管" class="filter-item" clearable />
      <el-input placeholder="请输入仓容量" class="filter-item" clearable />
      <el-input placeholder="请输入仓库地址" class="filter-item" clearable />
      <div class="filter-actions">
        <el-button>重置</el-button>
        <el-button type="primary">查询</el-button>
      </div>
    </div>
    <el-table :data="pagedOptions" border height="420px" :row-key="getRowKey" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="60" align="center" />
      <el-table-column type="index" label="序号" width="60" align="center" />
      <el-table-column prop="warehouseCode" label="仓库编号" width="180" />
      <el-table-column prop="warehouseName" label="仓库名称" width="120" />
      <el-table-column prop="warehouseCapacity" label="仓库容量/m³" width="140" />
      <el-table-column prop="warehouseAddress" label="仓库地址" min-width="260" show-overflow-tooltip />
      <el-table-column prop="organizationName" label="库管部门" width="160" show-overflow-tooltip />
      <el-table-column prop="userName" label="仓库主管" width="120" />
      <el-table-column label="仓库状态" width="120">
        <template #default="{ row }">
          <span v-if="row.warehouseState === 1">启用</span>
          <span v-else-if="row.warehouseState === 2">停用</span>
          <span v-else-if="row.warehouseState === 3">已锁定</span>
          <span v-else>--</span>
        </template>
      </el-table-column>
    </el-table>

    <div class="dialog-pagination">
      <div>总 {{ totalCount }} 条</div>
      <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[10, 20, 50]"
        layout="sizes, prev, pager, next" :total="totalCount" background />
      <el-select v-model="pageSize" class="page-size-select" style="width: 120px">
        <el-option label="10条/页" :value="10" />
        <el-option label="20条/页" :value="20" />
        <el-option label="50条/页" :value="50" />
      </el-select>
    </div>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="cancelSelection">取消</el-button>
        <el-button type="primary" @click="confirmSelection">确定</el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 上传图片 -->
  <el-card style="margin-top: 20px;">
    <h4>上传图片</h4>
    <el-divider />
    <div style="color:#999; margin-bottom:8px;">您可以上传png、jpg、jpeg、gif格式的文件，单个图片最大不能超过10MB，最多可上传10张。保存时与表单一并提交。</div>
    <el-upload ref="imageUploadRef" list-type="picture-card" v-model:file-list="imageList" :multiple="true" :limit="10"
      :auto-upload="false" accept=".png,.jpg,.jpeg,.gif" :on-change="onImageChange" :on-remove="onImageRemove">
      <el-icon>
        <Plus />
      </el-icon>
    </el-upload>
  </el-card>

  <!-- 上传附件 -->
  <el-card style="margin-top: 20px;margin-bottom: 20px;">
    <h4>上传附件</h4>
    <el-divider />
    <div style="color:#999; margin-bottom:8px;">您可以上传任意常见格式文件，单个文件最大不能超过200MB。保存时与表单一并提交。</div>
    <el-upload ref="fileUploadRef" list-type="text" v-model:file-list="fileList" :multiple="true" :auto-upload="false"
      :on-change="onFileChange" :on-remove="onFileRemove">
      <el-button type="primary">选择文件</el-button>
      <template #tip>
        <div style="color:#999; margin-left:10px;">您可以上传doc、pdf、zip等常见格式文件</div>
      </template>
    </el-upload>
  </el-card>

  <!-- 浮框 -->
  <el-affix position="bottom" :offset="20">
    <el-card style="height: 80px;">
      <div style="float: right;">
        <!-- 统一显示一个"保存"按钮，保存所有内容（表单数据、图片、附件） -->
        <el-button type="success" @click="submitForm(ruleFormRef)" style="margin-bottom: 15px;">保存</el-button>
        <el-button type="info" @click="router.push({ path: '/GetProdut' })" style="margin-bottom: 15px;">取消</el-button>
      </div>
    </el-card>
  </el-affix>
</template>

<script lang="ts" setup>
import { onMounted, reactive } from 'vue'

import { type FormInstance, type FormRules } from 'element-plus'

import myaxios from '@/http/MyAxios'
import { useRoute, useRouter } from 'vue-router'
import { Plus } from '@element-plus/icons-vue'

const ruleFormRef = ref<FormInstance>()
const generatingProductCode = ref(false)

const TIME_SEGMENT_ORDER = ['YYYY', 'YY', 'MM', 'DD', 'HH', 'MI', 'SS']
const pad = (n: number, len = 2) => `${n}`.padStart(len, '0')

const buildCodeFromRule = (rule: any) => {
  const now = new Date()
  const segments = (rule?.timeRule || '')
    .split(',')
    .map((s: string) => s.trim().toUpperCase())
    .filter(Boolean)
    .sort((a: string, b: string) => {
      const idxA = TIME_SEGMENT_ORDER.indexOf(a)
      const idxB = TIME_SEGMENT_ORDER.indexOf(b)
      if (idxA === -1 && idxB === -1) return 0
      if (idxA === -1) return 1
      if (idxB === -1) return -1
      return idxA - idxB
    })
  const timePart = segments
    .map((seg: string) => {
      switch (seg) {
        case 'YYYY': return String(now.getFullYear())
        case 'YY': return String(now.getFullYear()).slice(-2)
        case 'MM': return pad(now.getMonth() + 1)
        case 'DD': return pad(now.getDate())
        case 'HH': return pad(now.getHours())
        case 'MI': return pad(now.getMinutes())
        case 'SS': return pad(now.getSeconds())
        default: return ''
      }
    })
    .join('')
  const serialLength = Number(rule?.serialLength ?? 3)
  const serial = '1'.padStart(serialLength > 0 ? serialLength : 3, '0')
  return `${rule?.codePrefix || ''}${timePart}${serial}`
}

const requestNumber = async (targetCode: string, targetName: string) => {
  try {
    const res = await myaxios.get('/api/Number/GenerateNumber', {
      params: { targetCode, targetName }
    })
    if (res?.data?.code === 200 && res?.data?.data) {
      return String(res.data.data)
    }
    throw new Error(res?.data?.message || '生成编号失败')
  } catch (err) {
    console.warn(`[numbering] GenerateNumber 接口不可用 (${targetCode})，尝试规则生成`, err)
    const ruleRes = await myaxios.get('/api/Number/QueryNumberingRules', {
      params: { targetCode, targetName }
    })
    const list = Array.isArray(ruleRes?.data?.data) ? ruleRes.data.data : []
    if (list.length > 0) {
      return buildCodeFromRule(list[0])
    }
    throw new Error('未找到对应的编号规则，请先配置编号规则')
  }
}

const generateProductCode = async () => {
  if (generatingProductCode.value) return
  generatingProductCode.value = true
  try {
    ruleForm.productCode = await requestNumber('Product', '货品')
    ElMessage.success('编号生成成功')
  } catch (error: any) {
    ElMessage.error(error?.message || '生成编号失败')
  } finally {
    generatingProductCode.value = false
  }
}

// ----------------------------------------------------------------------
// 图片/附件上传
const imageList = ref<any[]>([])  //货品图片
const fileList = ref<any[]>([])   //货品附件
const imageUploadRef = ref()
const fileUploadRef = ref()

// 统一校验
const validateImage = (raw: File) => {
  const okType = /\.(png|jpg|jpeg|gif)$/i.test(raw.name)
  if (!okType) { ElMessage.error('仅支持 png/jpg/jpeg/gif 图片'); return false }
  const okSize = raw.size / 1024 / 1024 < 10
  if (!okSize) { ElMessage.error('单个图片不能超过10MB'); return false }
  return true
}
const validateFile = (raw: File) => {
  const okSize = raw.size / 1024 / 1024 < 200
  if (!okSize) { ElMessage.error('单个文件不能超过200MB'); return false }
  return true
}

// 选择变更（不自动上传，仅收集）
const onImageChange = (file: any, list: any[]) => {
  const raw = file?.raw as File
  if (raw && !validateImage(raw)) {
    imageList.value = list.filter(x => x.uid !== file.uid)
    return
  }
  imageList.value = list
}

//移除图片
const onImageRemove = (file: any, list: any[]) => {
  imageList.value = list
}

//上传文件
const onFileChange = (file: any, list: any[]) => {
  const raw = file?.raw as File
  if (raw && !validateFile(raw)) {
    fileList.value = list.filter(x => x.uid !== file.uid)
    return
  }
  fileList.value = list
}

//移除文件
const onFileRemove = (file: any, list: any[]) => {
  fileList.value = list
}

const loadMedia = (pid: number) => {
  if (!pid) return
  // API服务器地址（与后端保持一致）
  const apiBaseUrl = 'http://localhost:8080'

  // images
  myaxios({ url: '/api/Product/GetProductMedia', method: 'get', params: { productId: pid, mediaType: 1 } })
    .then(res => {
      const arr = Array.isArray(res.data.data) ? res.data.data : []
      imageList.value = arr.map((m: any) => ({
        name: m.name || m.url,
        url: m.url.startsWith('http') ? m.url : `${apiBaseUrl}${m.url}`,  // 拼接完整URL
        status: 'success',
        mediaId: m.mediaId,
        size: m.size
      }))
    })
  // files
  myaxios({ url: '/api/Product/GetProductMedia', method: 'get', params: { productId: pid, mediaType: 2 } })
    .then(res => {
      const arr = Array.isArray(res.data.data) ? res.data.data : []
      fileList.value = arr.map((m: any) => ({
        name: m.name || m.url,
        url: m.url.startsWith('http') ? m.url : `${apiBaseUrl}${m.url}`,  // 拼接完整URL
        status: 'success',
        mediaId: m.mediaId,
        size: m.size
      }))
    })
}
//保存附件（编辑模式：删除旧媒体并上传新的；新增模式：创建并上传）
const saveAndCreateAnother = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  if (!ruleForm.productCode) {
    await generateProductCode()
    if (!ruleForm.productCode) {
      ElMessage.warning('请先生成货品编号')
      return
    }
  }
  await formEl.validate(async (valid) => {
    if (!valid) return

    // 判断是否为编辑模式
    const isEditMode = route.query.productId != null

    try {
      let productId: number

      if (isEditMode) {
        // 编辑模式：使用现有的productId
        productId = Number(route.query.productId)

        // 1. 先逻辑删除该产品的所有旧媒体（图片+附件）
        const oldImages = imageList.value.filter(x => x.mediaId)
        const oldFiles = fileList.value.filter(x => x.mediaId)
        const allOldMedia = [...oldImages, ...oldFiles]

        for (const media of allOldMedia) {
          try {
            await myaxios({
              url: '/api/Product/DeleteProductMedia',
              method: 'delete',
              params: { mediaId: media.mediaId },
            })
          } catch (err) {
            console.error('删除旧媒体失败:', err)
          }
        }

      } else {
        // 新增模式：创建货品并获取productId
        ruleForm.productShelfday = productShelfdayinfo.number + productShelfdayinfo.unit
        ruleForm.productShelf = productShelfdayinfo.check == true ? 1 : 2
        const rawProduct = { ...toRaw(ruleForm) }
        const productSanitized = {
          ...rawProduct,
          producttypeId: rawProduct.producttypeId === '' || rawProduct.producttypeId === null ? 0 : Number(rawProduct.producttypeId),
          supplierId: rawProduct.supplierId === '' || rawProduct.supplierId === null ? 0 : Number(rawProduct.supplierId),
          customerId: rawProduct.customerId === '' || rawProduct.customerId === null ? 0 : Number(rawProduct.customerId),
          productInmoney: rawProduct.productInmoney === '' || rawProduct.productInmoney === null ? 0 : Number(rawProduct.productInmoney),
          productOutmoney: rawProduct.productOutmoney === '' || rawProduct.productOutmoney === null ? 0 : Number(rawProduct.productOutmoney),
          productState: rawProduct.productState === '' || rawProduct.productState === null ? 1 : Number(rawProduct.productState),
          productOrderby: rawProduct.productOrderby === '' || rawProduct.productOrderby === null ? 0 : Number(rawProduct.productOrderby),
        }
        const payload = {
          product: productSanitized,
          inventories: buildInventoryPayload(),
        }
        const res = await myaxios({ url: '/api/Product/CreateProductWithMediaInit', method: 'post', data: payload })
        if (res.data.code !== 200) {
          ElMessage.error(res.data.message || '保存失败')
          return
        }
        productId = res.data.data as number
      }

      // 2. 上传新选择的图片（只上传带raw的新文件）
      for (const f of imageList.value) {
        if (!f.raw) continue
        const fd = new FormData()
        fd.append('file', f.raw)
        fd.append('productId', String(productId))
        fd.append('mediaType', '1')
        const ur = await myaxios({
          url: '/api/Product/UploadProductMedia',
          method: 'post',
          data: fd,
          headers: { Authorization: (typeof localStorage !== 'undefined' ? (localStorage.getItem('token') || '') : ''), 'Content-Type': 'multipart/form-data' },
        })
        if (ur.data.code !== 200) throw new Error(ur.data.message || '图片上传失败')
      }

      // 3. 上传新选择的附件（只上传带raw的新文件）
      for (const f of fileList.value) {
        if (!f.raw) continue
        const fd = new FormData()
        fd.append('file', f.raw)
        fd.append('productId', String(productId))
        fd.append('mediaType', '2')
        const ur = await myaxios({
          url: '/api/Product/UploadProductMedia',
          method: 'post',
          data: fd,
          headers: { Authorization: (typeof localStorage !== 'undefined' ? (localStorage.getItem('token') || '') : ''), 'Content-Type': 'multipart/form-data' },
        })
        if (ur.data.code !== 200) throw new Error(ur.data.message || '附件上传失败')
      }

      ElMessage.success(isEditMode ? '附件保存成功' : '保存并上传成功')
      router.push('GetProdut')

      // 仅新增模式清空表单
      if (!isEditMode) {
        Object.assign(ruleForm, {
          productId: 0,
          productName: '',
          productCode: '',
          productState: null,
          producttypeId: '',
          productUnit: '',
          productBarcode: '',
          supplierId: null,
          customerId: '',
          productInmoney: null,
          productOutmoney: null,
          productShelf: 0,
          isDelete: false,
          productOrderby: null,
          productShelfday: '',
          productNote: '',
          inventoryId: 1,
          productWarningDay: '',
          productspecification: '',
          productFile: '',
          productPic: '',
          createor: '',
          createrTime: null,
          updater: '',
          updateTime: null
        })
        productShelfdayinfo.number = ''
        productShelfdayinfo.unit = ''
        productShelfdayinfo.check = null
        rows.value = []
        imageList.value = []
        fileList.value = []
      }
    } catch (e: any) {
      ElMessage.error(e?.message || '操作失败')
    }
  })
}

const router = useRouter();
const route = useRoute();


//------------------------------------------------------------------------------------------------------
import { computed, ref, watch, toRaw } from 'vue'
import { ElMessage } from 'element-plus'

interface WarehouseRow {
  warehouseId: number | null
  warehouseCode: string
  warehouseName: string
  initialStock: string
  initialAmount: string
  upperLimit: string
  lowerLimit: string
  remark: string
}

interface WarehouseOption {
  warehouseId: number
  warehouseCode: string
  warehouseName: string
  warehouseCapacity?: number
  warehouseAddress?: string
  organizationName?: string
  userName?: string
  warehouseState?: number
}

interface InventoryPayload {
  warehouseId: number
  warehouseCode: string
  warehouseName: string
  initialStock: number | null
  initialAmount: number | null
  upperLimit: number | null
  lowerLimit: number | null
  remark: string
}

type BatchField = 'warehouseName' | 'initialStock' | 'initialAmount' | 'upperLimit' | 'lowerLimit' | 'remark'

const showInitial = ref(true)

//库存表单
const rows = ref<WarehouseRow[]>([])

const limitError = ref(false)

// 添加一行
const createEmptyRow = (index: number): WarehouseRow => ({
  warehouseId: null,
  warehouseCode: '',
  warehouseName: `仓库${index}`,
  initialStock: '',
  initialAmount: '',
  upperLimit: '',
  lowerLimit: '',
  remark: '',
})

const dialogVisible = ref(false)

// 仓库列表数据
const warehouseOptions = ref<WarehouseOption[]>([])
const warehouseLoading = ref(false)

const currentPage = ref(1)
const pageSize = ref(10)

const pagedOptions = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  return warehouseOptions.value.slice(start, start + pageSize.value)
})

const totalCount = computed(() => warehouseOptions.value.length)

const selectedIds = ref<number[]>([])

// 打开仓库列表弹框
const openDialog = () => {
  dialogVisible.value = true
}

// 移除
const removeLast = () => {
  if (!rows.value.length) return
  rows.value.pop()
  validateLimits()
}

//移除一行
const removeRow = (index: number) => {
  rows.value.splice(index, 1)
  validateLimits()
}

// 选择仓库
const confirmSelection = () => {
  if (!selectedIds.value.length) {
    ElMessage.warning('请至少选择一个仓库')
    return
  }
  rows.value = selectedIds.value.map((id, index) => {
    const warehouse = warehouseOptions.value.find((item) => item.warehouseId === id) //仓库id
    if (!warehouse) {
      return createEmptyRow(index + 1)
    }
    return {
      warehouseId: warehouse.warehouseId,
      warehouseCode: warehouse.warehouseCode,
      warehouseName: warehouse.warehouseName,
      initialStock: '',
      initialAmount: '',
      upperLimit: '',
      lowerLimit: '',
      remark: '',
    }
  })
  dialogVisible.value = false
  validateLimits()
}

//仓库列表弹框
const cancelSelection = () => {
  dialogVisible.value = false
}

//仓库列表弹框-复选框
const handleSelectionChange = (selection: WarehouseOption[]) => {
  selectedIds.value = selection.map((item) => item.warehouseId)
}

//获取仓库id
const getRowKey = (row: WarehouseOption) => row.warehouseId


//批量
const handleBatch = (field: BatchField, value: string) => {
  if (!value) {
    ElMessage.warning('请先填写要批量设置的值')
    return
  }
  rows.value.forEach((item) => {
    item[field] = value
  })
  validateLimits()
}


//保存列表数据
const validateLimits = () => {
  const hasError = rows.value.some((row) => {
    if (row.upperLimit === '' || row.lowerLimit === '') return false
    const upper = Number(row.upperLimit)
    const lower = Number(row.lowerLimit)
    return !Number.isNaN(upper) && !Number.isNaN(lower) && upper <= lower
  })
  //判断库存上限是否大于库存下限
  if (hasError) {
    if (!limitError.value) {
      ElMessage.error('库存上限应大于库存下限！')
    }
    limitError.value = true
  }
  else {
    limitError.value = false
  }
}

const toNumberOrNull = (value: string) => {
  if (value === undefined || value === null) {
    return null
  }
  const trimmed = value.toString().trim()
  if (trimmed === '') {
    return null
  }
  const num = Number(trimmed)
  return Number.isNaN(num) ? null : num
}

const toIntOrNull = (value: string) => {
  const num = toNumberOrNull(value)
  return num === null ? null : Math.floor(num)
}

const buildInventoryPayload = (): InventoryPayload[] => {
  return rows.value
    .filter((item) => item.warehouseId !== null && item.warehouseId !== undefined)
    .map((item) => ({
      warehouseId: item.warehouseId as number,
      warehouseCode: item.warehouseCode,
      warehouseName: item.warehouseName,
      initialStock: toIntOrNull(item.initialStock),
      initialAmount: toNumberOrNull(item.initialAmount),
      upperLimit: toIntOrNull(item.upperLimit),
      lowerLimit: toIntOrNull(item.lowerLimit),
      remark: item.remark,
    }))
}

//选择仓库数据
const syncDefaultWarehouseRows = () => {
  if (rows.value.length || !warehouseOptions.value.length) {
    return
  }
  rows.value = warehouseOptions.value.slice(0, 5).map((warehouse) => ({
    warehouseId: warehouse.warehouseId,
    warehouseCode: warehouse.warehouseCode,
    warehouseName: warehouse.warehouseName,
    initialStock: '',
    initialAmount: '',
    upperLimit: '',
    lowerLimit: '',
    remark: '',
  }))
}

//获取仓库数据
const fetchWarehouseOptions = async () => {
  if (warehouseLoading.value) return
  warehouseLoading.value = true
  try {
    const res = await myaxios({
      url: '/api/Warehouse/GetWarehouse',
      method: 'get',
      params: {
        pageindex: 1,
        pagesize: 999,
      },
    })
    const responseData = res.data?.data
    if (res.data.code === 200 && responseData?.data && Array.isArray(responseData.data)) {
      warehouseOptions.value = responseData.data.map((item: any) => ({
        warehouseId: item.warehouseId,
        warehouseCode: item.warehouseCode,
        warehouseName: item.warehouseName,
        warehouseCapacity: item.warehouseCapacity,
        warehouseAddress: item.warehouseAddress,
        organizationName: item.organizationName,
        userName: item.userName,
        warehouseState: item.warehouseState,
      }))
      syncDefaultWarehouseRows()
    } else {
      warehouseOptions.value = []
      ElMessage.error(res.data.message || '获取仓库数据失败')
    }
  } catch (error) {
    warehouseOptions.value = []
    console.error(error)
    ElMessage.error('获取仓库数据异常，请稍后重试')
  } finally {
    warehouseLoading.value = false
  }
}

//------------------------------------------------------------------------------------------------------
//保质期信息（必须在 Fetail 函数之前定义，因为 Fetail 函数会使用它）
const productShelfdayinfo: any = reactive({
  number: "",
  unit: "",
  check: false,//是否开启
})

//------------------------------------------------------------------------------------------------------
//详情
const Fetail = async () => {
  const productId = Number(route.query.productId);
  if (!productId) {
    ElMessage.error('缺少货品ID');
    return;
  }

  try {
    // 通过API获取完整的货品信息
    const res = await myaxios({
      url: '/api/Product/GetProductById',
      method: 'get',
      params: { productId: productId }
    });

    if (res.data.code === 200 && res.data.data) {
      const data = res.data.data;

      // 反填基础信息
      ruleForm.productId = data.productId;
      ruleForm.productName = data.productName || '';
      ruleForm.productCode = data.productCode || '';
      ruleForm.productState = data.productState?.toString() || '1';
      ruleForm.producttypeId = data.producttypeId || '';
      // productUnit 可能是单位ID（数字）或单位名称（字符串）
      // 如果是字符串，需要查找对应的单位ID
      if (typeof data.productUnit === 'string' && data.productUnit) {
        const unit = unitOptions.value.find((u: any) => u.unitName === data.productUnit)
        ruleForm.productUnit = unit ? unit.unitId : ''
      } else {
        ruleForm.productUnit = data.productUnit || '';
      }
      ruleForm.productBarcode = data.productBarcode || '';
      ruleForm.supplierId = data.supplierId || null;
      ruleForm.customerId = data.customerId || '';
      ruleForm.productInmoney = data.productInmoney || null;
      ruleForm.productOutmoney = data.productOutmoney || null;
      ruleForm.productOrderby = data.productOrderby || null;
      ruleForm.productNote = data.productNote || '';
      ruleForm.productWarningDay = data.productWarningDay || '';
      ruleForm.productspecification = data.productspecification || '';

      // 设置创建人和更新人信息
      ruleForm.createor = data.createor || '';
      ruleForm.createrTime = data.createrTime || null;
      ruleForm.updater = data.updater || '';
      ruleForm.updateTime = data.updateTime || null;

      // 处理保质期信息
      if (data.productShelfday) {
        const shelfday = data.productShelfday.toString();
        // 解析保质期，例如 "30天" -> number: "30", unit: "天"
        const match = shelfday.match(/^(\d+)(.*)$/);
        if (match) {
          productShelfdayinfo.number = match[1];
          productShelfdayinfo.unit = match[2] || '天';
        } else {
          productShelfdayinfo.number = shelfday;
          productShelfdayinfo.unit = '天';
        }
      }
      productShelfdayinfo.check = data.productShelf === 1;

      // 加载图片和附件
      loadMedia(data.productId);

    } else {
      ElMessage.error(res.data.message || '获取货品信息失败');
      return;
    }
  } catch (error) {
    console.error('获取货品信息失败:', error);
    ElMessage.error('获取货品信息失败，请稍后重试');
    return;
  }

  // 根据货品ID获取库存明细并反填
  try {
    const res = await myaxios({
      url: '/api/Product/GetInventoryByProductId',
      method: 'get',
      params: {
        productId: ruleForm.productId,
      },
    })
    if (res.data.code === 200 && res.data.data && Array.isArray(res.data.data)) {
      // 将库存数据填充到 rows 数组中
      rows.value = res.data.data.map((item: any) => ({
        warehouseId: item.warehouseId,
        warehouseCode: item.warehouseCode || '',
        warehouseName: item.warehouseName || '',
        initialStock: item.initialStock?.toString() || '',
        initialAmount: item.initialAmount?.toString() || '',
        upperLimit: item.upperLimit?.toString() || '',
        lowerLimit: item.lowerLimit?.toString() || '',
        remark: item.remark || '',
      }))
      validateLimits()
    } else {
      // 如果没有库存数据，清空库存表格
      rows.value = []
    }
  } catch (error) {
    console.error('获取库存明细失败:', error)
    ElMessage.error('获取库存明细失败，请稍后重试')
    rows.value = []
  }
}

//获取条形码
const GetproductBarcode = () => {
  ruleForm.productBarcode = "000000" + Math.random().toString().substring(2, 5);
}

//货品表单
const ruleForm: any = reactive({
  productId: 0,//货品id
  productName: "",//货品名称
  productCode: "",//货品编号
  productState: null,//状态
  producttypeId: "",//货品类型
  productUnit: "",//规格型号
  productBarcode: "",//条码
  supplierId: null,//供应商
  customerId: "",//客户名称
  productInmoney: null,//入库参考价/元
  productOutmoney: null,//出库参考价/元
  productShelf: 0,//保质期管理
  isDelete: false,//是否删除
  productOrderby: null,//显示顺序
  productShelfday: "",//保质期
  productNote: "",//备注
  inventoryId: 1,//库存id
  productWarningDay: "",//预警天数(天) 保持空串避免后端非空字符串校验
  productspecification: "",//规格
  productFile: "",//货品附件，空串避免必填校验
  productPic: "",//货品图片，空串避免必填校验
  createor: "",//创建人
  createrTime: null,//创建时间
  updater: "",//更新人
  updateTime: null//更新时间
})

const setShelfFields = () => {
  ruleForm.productShelf = productShelfdayinfo.check ? 1 : 2
  if (!productShelfdayinfo.check) {
    productShelfdayinfo.number = ""
    productShelfdayinfo.unit = ""
    ruleForm.productShelfday = ""
    ruleForm.productWarningDay = ""
  }
}

//验证规则
const rules = reactive<FormRules>({
  productName: [
    { required: true, message: '请输入货品名称', trigger: 'blur' },
    { min: 2, max: 10, message: '长度必须在2-10个字符之间', trigger: 'blur' },
  ],
  productState: [
    {
      required: true,
      message: '请选择货品状态',
      trigger: 'change',
    },
  ],
  producttypeId: [
    {
      required: true,
      message: '请选择货品类型',
      trigger: 'change',
    },
  ],
  productUnit: [
    {
      required: true,
      message: '请输入规格型号',
      trigger: 'blur',
    },
  ],
  productBarcode: [
    {
      required: true,
      message: '请输入条形码',
      trigger: 'blur',
    },
  ],
  supplierId: [
    {
      required: true,
      message: '请选择供应商',
      trigger: 'change',
    },
  ],
  customerId: [
    {
      required: true,
      message: '请选择客户名称',
      trigger: 'change',
    },
  ],
  productInmoney: [
    {
      required: true,
      message: '请输入入库参考价/元',
      trigger: 'blur',
    },
  ],
  productOutmoney: [
    {
      required: true,
      message: '请输入出库参考价/元',
      trigger: 'blur',
    },
  ],
  productOrderby: [
    {
      required: true,
      message: '请输入显示顺序',
      trigger: 'blur',
    },
  ],
  productNote: [
    {
      required: true,
      message: '请输入备注',
      trigger: 'blur',
    },
  ],
  productWarningDay: [
    {
      required: true,
      message: '请输入预警天数',
      trigger: 'blur',
    },
  ],
})

//保存货品信息
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  if (!ruleForm.productCode) {
    await generateProductCode()
    if (!ruleForm.productCode) {
      ElMessage.warning('请先添加货品信息')
      return
    }
  }
  // 自动生成条形码（如果为空）
  if (!ruleForm.productBarcode || ruleForm.productBarcode.trim() === '') {
    GetproductBarcode()
  }
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      ruleForm.productShelfday = productShelfdayinfo.number + productShelfdayinfo.unit
      ruleForm.productShelf = productShelfdayinfo.check == true ? 1 : 2
      const rawProduct = { ...toRaw(ruleForm) }
      const productSanitized = {
        ...rawProduct,
        producttypeId: rawProduct.producttypeId === '' || rawProduct.producttypeId === null ? 0 : Number(rawProduct.producttypeId),
        supplierId: rawProduct.supplierId === '' || rawProduct.supplierId === null ? 0 : Number(rawProduct.supplierId),
        customerId: rawProduct.customerId === '' || rawProduct.customerId === null ? 0 : Number(rawProduct.customerId),
        productInmoney: rawProduct.productInmoney === '' || rawProduct.productInmoney === null ? 0 : Number(rawProduct.productInmoney),
        productOutmoney: rawProduct.productOutmoney === '' || rawProduct.productOutmoney === null ? 0 : Number(rawProduct.productOutmoney),
        productState: rawProduct.productState === '' || rawProduct.productState === null ? 1 : Number(rawProduct.productState),
        productOrderby: rawProduct.productOrderby === '' || rawProduct.productOrderby === null ? 0 : Number(rawProduct.productOrderby),
        // productUnit 应该是单位ID（数字），如果已经是数字则直接使用，否则尝试转换
        productUnit: (() => {
          const unitValue = rawProduct.productUnit
          if (unitValue === '' || unitValue === null || unitValue === undefined) {
            return 0
          }
          // 如果已经是数字，直接返回
          if (typeof unitValue === 'number') {
            return unitValue
          }
          // 如果是字符串，尝试转换为数字
          const numValue = Number(unitValue)
          // 如果转换失败（NaN），尝试通过单位名称查找单位ID
          if (isNaN(numValue)) {
            const unit = unitOptions.value.find((u: any) => u.unitName === unitValue || String(u.unitId) === String(unitValue))
            return unit ? Number(unit.unitId) : 0
          }
          return numValue
        })(),
      }
      const payload = {
        product: productSanitized,
        inventories: buildInventoryPayload(),
      }
      //修改
      if (route.query.productId != null) {
        try {
          const productId = Number(route.query.productId)
          
          // 1. 先批量逻辑删除现有库存数据
          const deleteRes = await myaxios({
            url: '/api/Product/DeleteInventoryByProductId',
            method: 'post',
            data: { productId },
          })

          if (deleteRes.data.code !== 200) {
            ElMessage.error(deleteRes.data.message)
            return
          }

          // 2. 确保productSanitized包含productId和所有必需字段
          const productWithId = {
            ...payload.product,
            productId,
            // 确保所有必需字段都有值
            productName: payload.product.productName || '',
            productCode: payload.product.productCode || '',
            productState: payload.product.productState || 1,
            producttypeId: payload.product.producttypeId || 0,
            productUnit: payload.product.productUnit || 0,
            supplierId: payload.product.supplierId || 0,
            customerId: payload.product.customerId || 0,
            productInmoney: payload.product.productInmoney || 0,
            productOutmoney: payload.product.productOutmoney || 0,
            productOrderby: payload.product.productOrderby || 0,
            productShelf: payload.product.productShelf || 2,
            isDelete: payload.product.isDelete || false,
          }
          
          // 3. 更新产品信息
          const updateRes = await myaxios({
            url: '/api/Product/UpdateProduct',
            method: 'post',
            data: productWithId,
          })
          
          if (updateRes.data.code !== 200) {
            console.error('更新产品信息失败:', updateRes.data)
            const errorMsg = updateRes.data.message || '更新产品信息失败'
            console.error('发送的数据:', productWithId)
            ElMessage.error(errorMsg)
            return
          }

          // 4. 批量添加新的库存数据
          if (payload.inventories && payload.inventories.length > 0) {
            const inventoryRes = await myaxios({
              url: '/api/Product/BatchCreateInventory',
              method: 'post',
              data: {
                productId,
                inventories: payload.inventories,
              },
            })

            if (inventoryRes.data.code !== 200) {
              console.error('批量添加库存数据失败:', inventoryRes.data)
              ElMessage.error(inventoryRes.data.message || '批量添加库存数据失败')
              return
            }
          }

          // 5. 处理图片和附件
          // 5.1 获取当前产品所有媒体，用于对比删除
          let existingMedia: any[] = []
          try {
            const mediaRes = await myaxios({
              url: '/api/Product/GetProductMedia',
              method: 'get',
              params: { productId }
            })
            if (mediaRes.data?.code === 200) {
              existingMedia = Array.isArray(mediaRes.data.data) ? mediaRes.data.data : []
            }
          } catch (err) {
            console.warn('获取现有媒体失败:', err)
          }

          // 5.2 找出需要删除的媒体（在现有媒体中但不在当前列表中）
          const currentImageIds = imageList.value.filter(x => x.mediaId).map(x => x.mediaId)
          const currentFileIds = fileList.value.filter(x => x.mediaId).map(x => x.mediaId)
          const currentMediaIds = [...currentImageIds, ...currentFileIds]
          
          for (const media of existingMedia) {
            if (!currentMediaIds.includes(media.mediaId)) {
              // 这个媒体不在当前列表中，需要删除
              try {
                await myaxios({
                  url: '/api/Product/DeleteProductMedia',
                  method: 'delete',
                  params: { mediaId: media.mediaId },
                })
              } catch (err) {
                console.warn('删除媒体失败:', err)
              }
            }
          }

          // 5.3 上传新选择的图片（只上传带raw的新文件）
          for (const f of imageList.value) {
            if (!f.raw) continue
            const fd = new FormData()
            fd.append('file', f.raw)
            fd.append('productId', String(productId))
            fd.append('mediaType', '1')
            try {
              const ur = await myaxios({
                url: '/api/Product/UploadProductMedia',
                method: 'post',
                data: fd,
                headers: { 
                  Authorization: (typeof localStorage !== 'undefined' ? (localStorage.getItem('token') || '') : ''), 
                  'Content-Type': 'multipart/form-data' 
                },
              })
              if (ur.data.code !== 200) {
                console.warn('图片上传失败:', ur.data.message)
              }
            } catch (imgErr) {
              console.error('图片上传异常:', imgErr)
            }
          }

          // 5.4 上传新选择的附件（只上传带raw的新文件）
          for (const f of fileList.value) {
            if (!f.raw) continue
            const fd = new FormData()
            fd.append('file', f.raw)
            fd.append('productId', String(productId))
            fd.append('mediaType', '2')
            try {
              const ur = await myaxios({
                url: '/api/Product/UploadProductMedia',
                method: 'post',
                data: fd,
                headers: { 
                  Authorization: (typeof localStorage !== 'undefined' ? (localStorage.getItem('token') || '') : ''), 
                  'Content-Type': 'multipart/form-data' 
                },
              })
              if (ur.data.code !== 200) {
                console.warn('附件上传失败:', ur.data.message)
              }
            } catch (fileErr) {
              console.error('附件上传异常:', fileErr)
            }
          }

          ElMessage.success('保存成功')
          // 保存成功后跳转到货品列表
          router.push({ path: '/GetProdut' })
          
        } catch (err: any) {
          console.error('更新失败:', err)
          // 尝试获取更详细的错误信息
          if (err.response) {
            console.error('响应数据:', err.response.data)
            console.error('状态码:', err.response.status)
            // 如果是400错误，显示详细的验证错误信息
            if (err.response.status === 400 && err.response.data?.errors) {
              const errors = err.response.data.errors
              const errorMessages = Object.keys(errors).map(key => {
                const messages = Array.isArray(errors[key]) ? errors[key] : [errors[key]]
                return `${key}: ${messages.join(', ')}`
              }).join('; ')
              ElMessage.error(`验证失败: ${errorMessages}`)
            } else {
              ElMessage.error(err.response.data?.message || `更新失败: ${err.response.status}`)
            }
          } else if (err.request) {
            console.error('请求错误:', err.request)
            ElMessage.error('网络请求失败，请检查网络连接')
          } else {
            ElMessage.error(`更新失败: ${err.message}`)
          }
        }
      } else {
        // 新增模式：创建货品并上传图片和附件
        try {
          console.log('新增模式，发送的数据:', payload)
          
          // 1. 创建货品并获取productId
          const res = await myaxios({
            url: '/api/Product/CreateProductWithMediaInit',
            method: 'post',
            data: payload,
          })
          
          if (res.data.code !== 200) {
            ElMessage.error(res.data.message || '保存失败')
            return
          }
          
          const productId = res.data.data as number
          
          // 2. 上传图片（只上传带raw的新文件）
          for (const f of imageList.value) {
            if (!f.raw) continue
            const fd = new FormData()
            fd.append('file', f.raw)
            fd.append('productId', String(productId))
            fd.append('mediaType', '1')
            try {
              const ur = await myaxios({
                url: '/api/Product/UploadProductMedia',
                method: 'post',
                data: fd,
                headers: { 
                  Authorization: (typeof localStorage !== 'undefined' ? (localStorage.getItem('token') || '') : ''), 
                  'Content-Type': 'multipart/form-data' 
                },
              })
              if (ur.data.code !== 200) {
                console.warn('图片上传失败:', ur.data.message)
              }
            } catch (imgErr) {
              console.error('图片上传异常:', imgErr)
            }
          }

          // 3. 上传附件（只上传带raw的新文件）
          for (const f of fileList.value) {
            if (!f.raw) continue
            const fd = new FormData()
            fd.append('file', f.raw)
            fd.append('productId', String(productId))
            fd.append('mediaType', '2')
            try {
              const ur = await myaxios({
                url: '/api/Product/UploadProductMedia',
                method: 'post',
                data: fd,
                headers: { 
                  Authorization: (typeof localStorage !== 'undefined' ? (localStorage.getItem('token') || '') : ''), 
                  'Content-Type': 'multipart/form-data' 
                },
              })
              if (ur.data.code !== 200) {
                console.warn('附件上传失败:', ur.data.message)
              }
            } catch (fileErr) {
              console.error('附件上传异常:', fileErr)
            }
          }
          
          ElMessage.success('保存成功')
          // 保存成功后跳转到货品列表
          router.push({ path: '/GetProdut' })
          
        } catch (e: any) {
          console.error('新增失败:', e)
          console.error('请求数据:', payload)
          console.error('响应数据:', e?.response?.data)
          
          // 显示详细的错误信息
          let errorMsg = '保存失败'
          if (e?.response?.data) {
            if (e.response.data.message) {
              errorMsg = e.response.data.message
            } else if (e.response.data.errors) {
              // 处理验证错误
              const errors = e.response.data.errors
              const errorMessages = Object.keys(errors).map(key => {
                const messages = Array.isArray(errors[key]) ? errors[key] : [errors[key]]
                return `${key}: ${messages.join(', ')}`
              }).join('; ')
              errorMsg = `验证失败: ${errorMessages}`
            }
          } else if (e?.message) {
            errorMsg = e.message
          }
          ElMessage.error(errorMsg)
        }
      }
    } else {
      console.log('error submit!', fields)
    }
  })
}
//----------------------------------------------------------------------------
const unitOptions = ref<any[]>([])

const loadUnitOptions = () => {
  myaxios({
    url: '/api/Unit/GetUnitList',
    method: 'get',
  })
    .then(res => {
      console.log(res);
      unitOptions.value = res.data.data 
    })
    .catch(err => {
      console.error('获取单位列表失败:', err)
      console.error('请求URL:', err?.config?.url || err?.request?.responseURL || '/api/Unit/GetUnitList')
      console.error('完整请求URL:', err?.config?.baseURL + err?.config?.url || '未知')
      console.error('错误状态:', err?.response?.status)
      console.error('错误信息:', err?.response?.data || err?.message)
    })
}

//供应商信息接收
const SupplietableData: any = ref([])

//供应商信息请求
const GetSupplie = () => {
  myaxios({
    url: "/api/Product/GetSupplier",
    method: "get",
  })
    .then(res => {
      SupplietableData.value = res.data.data;
    })
    .catch(err => {
      console.log(err);
    })
}

//货品类型信息接收（扁平数据，保留用于兼容）
const ProductTypetableData: any = ref([])

//货品类型树形数据（用于树形选择器）
const ProductTypeTreeData = ref<any[]>([])

// 构建树形结构
const buildProductTypeTree = (items: any[]): any[] => {
  const tree: any[] = []
  const map: { [key: string]: any } = {}

  // 创建映射
  items.forEach(item => {
    map[item.producttypeId] = {
      id: item.producttypeId,
      label: item.producttypeName,
      children: []
    }
  })

  // 构建树
  items.forEach(item => {
    const parentId = item.producttypeParentid
    // 如果父级ID存在且不为0，且父级节点在map中，则作为子节点
    if (parentId && parentId !== 0 && map[parentId]) {
      map[parentId].children.push(map[item.producttypeId])
    } else {
      // 否则作为根节点
      tree.push(map[item.producttypeId])
    }
  })

  return tree
}

//货品类型信息请求
const GetProductType = () => {
  myaxios({
    url: "/api/Product/GetProductType",
    method: "get",
  })
    .then(res => {
      const allData = res.data.data || []
      // 保存扁平数据用于兼容
      ProductTypetableData.value = allData
      // 构建树形数据用于树形选择器
      ProductTypeTreeData.value = buildProductTypeTree(allData)
    })
    .catch(err => {
      console.log(err);
    })
}

//客户信息接收
const CustomertableData: any = ref([])

//客户信息请求
const GetCustomer = () => {
  myaxios({
    url: "/api/Product/GetCustomer",
    method: "get",
  })
    .then(res => {
      CustomertableData.value = res.data.data;
    })
    .catch(err => {
      console.log(err);
    })
}

watch(
  () => productShelfdayinfo.check,
  () => {
    setShelfFields()
  },
  { immediate: true }
)

//侦听器
watch(
  rows,//库存表单
  () => {
    validateLimits()
  },
  { deep: true }
)


watch(
  () => [productShelfdayinfo.number, productShelfdayinfo.unit],
  () => {
    if (productShelfdayinfo.check && productShelfdayinfo.number && productShelfdayinfo.unit) {
      ruleForm.productShelfday = `${productShelfdayinfo.number}${productShelfdayinfo.unit}`
    } else if (!productShelfdayinfo.check) {
      ruleForm.productShelfday = ''
    }
  },
  { immediate: true }
)

//钩子函数
onMounted(() => {
  GetSupplie();//供应商请求
  GetProductType();//货品类型信息请求
  GetCustomer();//客户信息请求
  loadUnitOptions();//单位列表
  fetchWarehouseOptions()
  if (route.query.productId != null) {
    Fetail()//详情信息
  }
})
</script>
<style scoped>
.inventory-card {
  min-height: 400px;
}

.inventory-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.inventory-header h4 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

.inventory-actions {
  display: flex;
  align-items: center;
  gap: 12px;
}

.inventory-alert {
  margin-bottom: 12px;
}

.cell-with-action {
  display: flex;
  align-items: center;
  gap: 8px;
}

.cell-with-action .el-input {
  flex: 1;
}

.inventory-header-cell {
  background-color: #f5f7fa;
  color: #303133;
  font-weight: 600;
  text-align: center;
}

.dialog-filter {
  display: grid;
  grid-template-columns: repeat(4, minmax(160px, 1fr));
  gap: 12px;
  margin-bottom: 16px;
}

.filter-item {
  width: 100%;
}

.filter-actions {
  display: flex;
  align-items: center;
  gap: 12px;
}

.dialog-pagination {
  margin-top: 16px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

:deep(.readonly-input .el-input__wrapper) {
  background-color: #f5f7fa;
}
</style>
